package com.litesuits.sdk.act;


import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import com.litesuits.android.log.Log;
import com.litesuits.common.utils.SdCardUtil;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.request.AbstractRequest;
import com.litesuits.http.response.Response;
import com.litesuits.sdk.LiteSdk;
import com.litesuits.sdk.R;
import com.litesuits.sdk.listener.AbsFragmentHttpListener;
import com.litesuits.sdk.listener.FragProgressHttpListener;
import com.litesuits.sdk.views.CustomDialog;
import com.litesuits.sdk.views.DefaultTipsView;
import com.litesuits.sdk.views.DefaultTitleBar;

import java.lang.reflect.Field;
import java.util.Timer;
import java.util.TimerTask;

/**
 * base support fragment for app.
 *
 * @author MaTianyu on 2015-05-07
 */
public class LiteFragment extends Fragment implements LiteSupport {
    protected String TAG = "LiteFragment";
    private Handler handler;
    private Timer timer;
    protected LiteActivity activity;
    private DefaultTitleBar titleBar;
    private DefaultTipsView multiTipsView;
    protected int currentPage = PAGE_START;
    protected boolean isFirstLoad = true;

    @Override
    public void onAttach(Activity activity) {
        TAG = this.getClass().getSimpleName();
        super.onAttach(activity);
        this.activity = (LiteActivity) activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            if (childFragmentManager != null) {
                childFragmentManager.setAccessible(true);
                childFragmentManager.set(this, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (isAutoLoad()) {
            loadDataStart();
        }
    }


    /* ________________ base methods  ________________ */
    public DefaultTitleBar getDefaultTitleBar() {
        if (titleBar == null) {
            titleBar = new DefaultTitleBar(this);
        }
        return titleBar;
    }

    public DefaultTipsView getDefaultTipsView() {
        if (multiTipsView == null) {
            multiTipsView = createTipsView();
            View realView = findRealView();
            if (multiTipsView != null) {
                if (realView != null) {
                    multiTipsView.setRealView(realView);
                }
                //multiTipsView.setOrientation(LinearLayout.VERTICAL);
            }
        }
        return multiTipsView;
    }

    /* ________________ over-ride methods  ________________ */
    public boolean isAutoLoad() {
        return true;
    }

    public void loadDataStart() {
    }

    public DefaultTipsView createTipsView() {
        DefaultTipsView tipsView = new DefaultTipsView(activity);
        return tipsView;
    }

    public View findRealView() {
        return null;
    }


    /* ________________ common methods  ________________ */
    public boolean isSdCardAvailable() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
    }

    public SdCardUtil.SDCardInfo getSdCardInfo() {
        return SdCardUtil.getSDCardInfo();
    }

    public int dip2px(int dip) {
        return dip2px((float) dip);
    }

    public int dip2px(float dip) {
        float density = activity.getResources().getDisplayMetrics().density;
        return (int) (density * dip + 0.5f);
    }

    public float px2dip(int px) {
        float density = activity.getResources().getDisplayMetrics().density;
        return px / density + 0.5f;
    }

    public PackageInfo getPackInfo() {
        try {
            return activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /* ________________ handler methods  ________________ */

    public Handler getHandler() {
        if (handler == null) {
            handler = new Handler(Looper.getMainLooper());
        }
        return handler;
    }

    public Timer getTimer() {
        if (timer == null) {
            timer = new Timer();
        }
        return timer;
    }

    public void runOnUiThreadDelay(Runnable runnable, long delayMillis) {
        getHandler().postDelayed(runnable, delayMillis);
    }

    public void removeUiThreadRunable(Runnable runnable) {
        getHandler().removeCallbacks(runnable);
    }

    public void runOnSubThread(Runnable runnable) {
        smartExecutor.execute(runnable);
    }

    public void runOnSubThreadDelay(final Runnable runnable, long delayMillis) {
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                runnable.run();
            }
        };
        getTimer().schedule(task, delayMillis);
    }

    /* ________________ log methods  ________________ */
    public void logv(String msg) {
        Log.v(TAG, msg);
    }

    public void logd(String msg) {
        Log.d(TAG, msg);
    }

    public void logi(String msg) {
        Log.i(TAG, msg);
    }

    public void logw(String msg) {
        Log.w(TAG, msg);
    }

    public void loge(String msg) {
        Log.e(TAG, msg);
    }

    /* ________________ activity methods ________________ */
    public void noTitle() {
        activity.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    }

    public void fullScreen() {
        activity.getWindow()
                .setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    public void startActivity(Class claxx) {
        startActivity(new Intent(activity, claxx));
    }

    public void startActivity(Class<?> cls, Bundle bundles) {
        if (bundles == null) {
            startActivity(new Intent(activity, cls));
        } else {
            startActivity(new Intent(activity, cls).putExtras(bundles));
        }
    }

    public void startActivityForResult(Class claxx, int requestCode) {
        startActivityForResult(new Intent(activity, claxx), requestCode);
    }

    public void startActivityForResult(Class<?> cls, Bundle bundles, int requestCode) {
        if (bundles == null) {
            startActivityForResult(new Intent(activity, cls), requestCode);
        } else {
            startActivityForResult(new Intent(activity, cls).putExtras(bundles), requestCode);
        }
    }

    public void finish() {
        activity.finish();
    }

    public void finish(int animIn, int animOut) {
        activity.finish();
        activity.overridePendingTransition(animIn, animOut);
    }

    /* ________________ toastor methods ________________ */
    public void toast(int msgID) {
        toastor.showSingletonToast(msgID);
    }

    public void toast(String msg) {
        toastor.showSingletonToast(msg);
    }

    /* ________________ dialog methods ________________ */
    public CustomDialog.Builder buildCustomDialog() {
        CustomDialog.Builder builder = new CustomDialog.Builder(activity);
        return builder;
    }

    public CustomDialog.Builder buildCustomDialog(int title, int msg) {
        CustomDialog.Builder builder = new CustomDialog.Builder(activity);
        builder.setTitle(title);
        builder.setMessage(msg);
        return builder;
    }

    public CustomDialog.Builder buildCustomDialog(String title, String msg) {
        CustomDialog.Builder builder = new CustomDialog.Builder(activity);
        builder.setTitle(title);
        builder.setMessage(msg);
        return builder;
    }

    public void dialogShow(int title, int msg) {
        CustomDialog.Builder builder = buildCustomDialog(title, msg);
        builder.setPositiveButton(R.string.tips_sure, null);
        builder.create().show();
    }

    public void dialogShow(int msgID) {
        dialogShow(0, msgID);
    }

    public void dialogShow(String msg) {
        dialogShow(null, msg);
    }

    public void dialogShow(String title, String msg) {
        CustomDialog.Builder builder = buildCustomDialog(title, msg);
        builder.setPositiveButton(R.string.tips_sure, null);
        builder.create().show();
    }

    /**
     * 代替toast的提示框
     *
     * @param msg
     */
    public void showTipDialog(String msg) {

        final Dialog dialog = buildCustomDialog().setMessage(msg).create();
        dialog.show();
        getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    dialog.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, 1500);

    }

    /* ________________ http listener methods ________________ */
    public abstract class FragmetHttpListener<T> extends AbsFragmentHttpListener<T> {
        public FragmetHttpListener() {
            super(LiteFragment.this);
        }

        @Override
        public void onSuccess(T t, Response<T> response) {
            super.onSuccess(t, response);
        }

        @Override
        public void onFailure(HttpException e, Response<T> response) {
            super.onFailure(e, response);
        }
    }

    public abstract class DialogHttpListener<T> extends FragmetHttpListener<T> {
        @Override
        public void onFailure(HttpException e, Response<T> response) {
            super.onFailure(e, response);
            LiteSdk.getInstance().getHttpExceptionHandler().via(activity).handleException(e);
        }
    }

    public abstract class ProgressHttpListener<T> extends FragProgressHttpListener<T> {
        public ProgressHttpListener() {
            super(LiteFragment.this);
        }

        public ProgressHttpListener(boolean isProgressCancelable) {
            super(LiteFragment.this, isProgressCancelable);
        }
    }

    public abstract class TipsHttpListener<T> extends FragmetHttpListener<T> {

        public void noData() {
            if (getDefaultTipsView() != null) {
                getDefaultTipsView().showNoData();
            }
        }

        @Override
        public void onStart(AbstractRequest<T> request) {
            super.onStart(request);
            if (getDefaultTipsView() != null) {
                getDefaultTipsView().showLoading();
            }
        }

        @Override
        public void onSuccess(T t, Response<T> response) {
            super.onSuccess(t, response);
            if (getDefaultTipsView() != null) {
                getDefaultTipsView().showRealView();
            }
        }

        @Override
        public void onFailure(HttpException e, Response<T> response) {
            super.onFailure(e, response);
            if (getDefaultTipsView() != null) {
                getDefaultTipsView().showNoNetwork();
            }
        }
    }

    public abstract class LoadMoreTipsHttpListener<T> extends FragmetHttpListener<T> {

        public boolean isFirstPage() {
            return currentPage == PAGE_START;
        }

        public boolean isFirstLoad() {
            return isFirstLoad;
        }

        public abstract void onLoadingMore();

        @Override
        public void onStart(AbstractRequest<T> request) {
            super.onStart(request);
            if (isFirstLoad() && getDefaultTipsView() != null) {
                getDefaultTipsView().showLoading();
            }
            if (!isFirstPage()) {
                onLoadingMore();
            }
        }

        @Override
        public void onSuccess(T t, Response<T> response) {
            super.onSuccess(t, response);
            if (isFirstLoad() && getDefaultTipsView() != null) {
                isFirstLoad = false;
                getDefaultTipsView().showRealView();
            }
        }

        @Override
        public void onFailure(HttpException e, Response<T> response) {
            super.onFailure(e, response);
            if (isFirstLoad() && getDefaultTipsView() != null) {
                getDefaultTipsView().showNoNetwork();
            }
        }

    }
}
